/*
 * Created on Apr 25, 2006
 */
package net.amsoft.iservice.management.util;

import java.util.HashMap;
import java.util.Map;

import net.amsoft.iservice.management.service.IBrokerManagerService;
import net.amsoft.iservice.util.exception.IServiceException;

import org.apache.log4j.Logger;

/**
 * @author mukta
 */
public class IBrokerUtil {
    
    private static Logger logger = Logger.getLogger(IBrokerUtil.class);
    
    /**
     * Returns IBroker data for specified ibroker
     * @param ibroker
     * @return Map
     */
    public static Map getIBrokerData(String ibroker, String serviceName)
    {
        Map oMap = null;
        serviceName = serviceName.toLowerCase();
        
        // Get IBroker Data Map
        try
        {
            logger.warn("getIBrokerData(): Trying to fetch IBroker data object");
//            if (serviceName.equals(IBrokerConstants.getProperty(IBrokerConstants.SERVICE_ISSO)))
//                oMap = ISSOService.getIBrokerData(ibroker);
//            else if (serviceName.equals(IBrokerConstants.getProperty(IBrokerConstants.SERVICE_ILINK)))
//                oMap = ILinkService.getBrokerData(ibroker);
//            else
//                oMap = IContactService.getBrokerData(ibroker);
            oMap = IBrokerManagerService.getIBrokerData(ibroker, serviceName);
        }
        catch (IServiceException e)
        {
            logger.error("getIBrokerData(): Error while trying to fetch IBroker object -> " + e.getStackTrace());
            e.printStackTrace();
        }
                    
        logger.info("getIBrokerData(): Returning IBroker Data -> " + oMap);
        return oMap;
    }

    /**
     * Returns Links data for an IBroker
     * @param ibroker
     * @return String
     */
    public static String getLinks(String ibroker, String serviceName)
    {
        // Get IBroker Data
        Map oMap = getIBrokerData(ibroker, serviceName);
        
        // Extract Links Data
        String linksData = "";
        if (oMap != null)
            linksData = getLinks(oMap);
        
        logger.info("getLinks(): Returning Links -> " + linksData);
        return linksData;
    }

    /**
     * Returns Links data for an IBroker
     * @param oMap
     * @return String
     */
    public static String getLinks(Map oMap)
    {
        String linksData = "";

		int len = oMap.size();
		for (int i=1; i<=len/2; i++)
		{
			// Search for name value pairs
			String key = "link" + i + "_text";
			String value = "link" + i + "_url";
			if (oMap.containsKey(key))
			{
				if ("".equals(linksData))
					linksData = (String) oMap.get(key) + "=" + (String) oMap.get(value);
				else
					linksData = linksData + ", " + (String) oMap.get(key) + "=" + (String) oMap.get(value);
			}
		}
        
        logger.info("getLinks(): Returning Links -> " + linksData);
        return linksData;
    }

    /**
     * Returns Ad-Banner data for an IBroker
     * @param oMap
     * @return String
     */
    public static String getAdBanner(String ibroker, String serviceName)
    {
        // Get IBroker Data
        Map oMap = getIBrokerData(ibroker, serviceName);
        
        // Extract Links Data
        String banner = "";
        if (oMap != null)
            banner = getAdBanner(oMap);
        
        logger.info("getAdBanner(): Returning Ad Banner -> " + banner);
        return banner;
    }
    
    /**
     * Returns Ad-Banner data for an IBroker
     * @param oMap
     * @return String
     */
    public static String getAdBanner(Map oMap)
    {
        String banner = "";

        if (oMap.containsKey("ad-banner"))
        {
            banner = (String) oMap.get("ad-banner");
        }
        
        logger.info("getAdBanner(): Returning Ad Banner -> " + banner);
        return banner;
    }

	/**
	 * Updates database when ad-banner image is changed
	 * @param serverName
	 * @param banner
	 */
    public static void processAdBanner(String ibroker, String banner, String serviceName)
	{
		// Get Old Data
		Map oMap = getIBrokerData(ibroker, serviceName);
		
    	// Remove old ad-banner value
		if ((oMap != null) && (oMap.containsKey("ad-banner")))
		{
		    logger.debug("processAdBanner(): Removing ad-banner data");
			oMap.remove("ad-banner");
		}
		
		// Create new data to be placed
        HashMap mIBData = new HashMap();
		mIBData.put("ad-banner", banner);
		if (oMap != null)
			mIBData.putAll(oMap);

		// Set new data and update DB
		boolean status = setIBrokerData(ibroker, mIBData, serviceName);
		
		if (status)
		    logger.debug("processAdBanner(): Database updated successfully");
		else 
		    logger.error("processAdBanner(): Error while updating database");
	}

    /**
     * Updates IBroker data in database
     * @param serverName
     * @param oHashMap
     * @return
     */
	private static boolean setIBrokerData(String ibroker, HashMap oHashMap, String serviceName)
	{
	    boolean status = true;
	    
        // Post new data to database
	    try
	    {
            logger.warn("setIBrokerData(): Updating database");
//            if (serviceName.equals(IBrokerConstants.getProperty(IBrokerConstants.SERVICE_ISSO)))
//                ISSOService.setIBrokerData(ibroker, oHashMap);
//            else if (serviceName.equals(IBrokerConstants.getProperty(IBrokerConstants.SERVICE_ILINK)))
//                ILinkService.setBrokerData(ibroker, oHashMap);
//            else
//                IContactService.setBrokerData(ibroker, oHashMap);
            IBrokerManagerService.setIBrokerData(ibroker, oHashMap, serviceName);
        }
	    catch (Exception e)
	    {
            logger.error("setIBrokerData(): Error while saving IBroker data -> " + e.getStackTrace());
            status = false;
        }
	    
        // Return status
	    logger.info("setIBrokerData(): Returning status -> " + status);
        return status;
	}
	
	public static void processLinks(String ibroker, String linksData, String serviceName)
	{
		String links[] = linksData.split(", ");
		String adBanner = "Image";

		// Get Old Data
		Map oMap = getIBrokerData(ibroker, serviceName);
		
        // Check if ad-banner data is present, retain its value
        if (oMap.containsKey("ad-banner"))
        {
    		adBanner = (String) oMap.get("ad-banner");
		    logger.info("processLinks(): Ad-banner value -> " + adBanner);
    	}
                
        // Create new data to be placed
        HashMap mIBData = new HashMap();
        int len = links.length;
        for (int i=0; i<len; i++)
        {
        	// Saves links in database in the following format:
        	// Eg. 	Link1 is "Home" ==> http://www.amsoft.net
        	//		Link2 is "Privacy Policy" ==> http://www.amsoft.net/policy.html
        	// This data will be saved as
        	//		link1_text	"Home"
        	//		link1_url	"http://www.amsoft.net"
        	//		link2_text	"Privacy Policy"
        	//		link2_url	"http://www.amsoft.net/policy.html"

            String name[] = links[i].split("=");
        	int j = i+1;
        	String key = "link" + j + "_text"; 
        	mIBData.put(key, name[0]);
        	key = "link" + j + "_url";
        	mIBData.put(key, name[1]);
        }
        mIBData.put("ad-banner", adBanner);

		// Set new data and update DB
		boolean status = setIBrokerData(ibroker, mIBData, serviceName);

		if (status)
		    logger.debug("processLinks(): Database updated successfully");
		else 
		    logger.error("processLinks(): Error while updating database");
	}
	
}
